/**
 * 
 */
package xj.toolkit.jmx;

import java.io.FileReader;
import java.io.IOException;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import bsh.Interpreter;

/**
 * @author hp
 *
 */
public class JMXStatusMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// create the Options
		Options options = new Options();
		options.addOption( 
				OptionBuilder.withArgName( "url" )
                .hasArg()
                .withDescription(  "JMX Service URL string ." )
                .create( "jmxurl" ) );
		
		options.addOption( 
				OptionBuilder.withArgName( "filename" )
                .hasArg()
                .withDescription(  "BeanShell script filename which create JMXClosure instance." )
                .create( "script" ) );

	    String	bsh = null;
	    String	url = null;
	    
		try {
			// create the command line parser
			CommandLineParser parser = new GnuParser();
			
		    // parse the command line arguments
		    CommandLine line = parser.parse( options, args );
		    
		    if( line.hasOption( "jmxurl" ) ) {
		        // print the value of block-size
		    	url = line.getOptionValue("jmxurl");
		    }
		    
		    if( line.hasOption( "script" ) ) {
		        // print the value of block-size
		    	bsh = line.getOptionValue("script");
		    }
		    
		    if ( null == url || null == bsh ) {
		    	// automatically generate the help statement
		    	HelpFormatter formatter = new HelpFormatter();
		    	formatter.printHelp( "status", options );
		    	System.exit(-1);
		    }
		}
		catch( ParseException exp ) {
		    System.out.println( "Unexpected exception:" + exp.getMessage() );
		    System.exit(-1);
		}
		
		JMXConnector 			jmxc = null;
		MBeanServerConnection 	mbsc = null;
		
        try {
    		JMXServiceURL serviceUrl = new JMXServiceURL(url);
			
    		jmxc = JMXConnectorFactory.connect(serviceUrl, null);

    		mbsc = jmxc.getMBeanServerConnection();
    		
            Interpreter inter = new Interpreter();
			JMXClosure closure = (JMXClosure)inter.eval(new FileReader(bsh));
			if ( null != closure ) {
				closure.execute(mbsc);
			}
		} catch (Exception e) {
			System.out.println("Maybe server not running, Error in get status via jmx:" + e);
		} 
		finally {
	    	if ( null != jmxc ) {
	    		try {
					jmxc.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	    		jmxc = null;
	    	}
		}

	}

}
